﻿using VIFON.BLL;
using VIFON.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VIFON
{
    public partial class frmBills : Telerik.WinControls.UI.RadForm
    {
        private static VIFON.BLL.Utilities.ControlMode CurrentMode = VIFON.BLL.Utilities.ControlMode.Normal;

        public frmBills()
        {
            InitializeComponent();
        }
        BLCustomer blCustomer = new BLCustomer();
        BLProduct blProduct = new BLProduct();
        BLBill blBill = new BLBill();
        BLBillDetails blBillDetails = new BLBillDetails();
        BLCar blCar = new BLCar();
        int BillId = -1;
        string keyword = string.Empty;
        private void frmBills_Load(object sender, EventArgs e)
        {
            ShowToolbar();
            LoadCustomer();
            LoadBillList();
            LoadProduct();
            loadCarList();            
        }
        private void loadCarList()
        {
            ddcarlist.DisplayMember = "CarId";
            ddcarlist.ValueMember = "CarId";
            ddcarlist.DataSource = blCar.GetCarList();
        }
        private void LoadProduct() // Load product for choose
        {
           
            ddProducts.DisplayMember = "ProductName";
            ddProducts.ValueMember = "Id";
            ddProducts.DataSource = blProduct.GetProducts(keyword);            
            ddProducts.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            ddProducts.AutoCompleteDataSource = AutoCompleteSource.ListItems;
        }
        private void LoadBillList()
        {
            grvhoadon.Rows.Clear();
            var list = blBill.GetBillList();
            if (list != null)
            {
                foreach (var l in list.OrderByDescending(x=>x.CreatedDate))
                {
                    Customer customer = new Customer();
                    customer = blCustomer.GetCustomerById(l.CustomerId);
                    grvhoadon.Rows.Add(l.Id, l.CustomerId,customer.CustomerName, l.CreatedDated, l.CarId, l.Stan, l.Notation,"Xem");
                }
            }
            grvhoadon.Refresh();
            this.Refresh();            
        }
        private void Loadbilldetails()
        {
            grvproduct.Rows.Clear();
            var list=blBillDetails.GetBillDetailListById(BillId);
            string productname = string.Empty;
              if(list!=null)
              {
                  
                  foreach(var l in list)
                  {
                      Product product = new Product();
                      product = blProduct.GetProductById(l.ProductId);
                      grvproduct.Rows.Add(l.BillId, l.ProductId,product.ProductName,l.Amounts);                 
                  }
              }
            
        }
        private void LoadCustomer()
        {           
            ddCustomerId.DisplayMember = "CustomerName";
            ddCustomerId.ValueMember = "Id";
            ddCustomerId.DataSource = blCustomer.GetCustomersList();
            ddCustomerId.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            ddCustomerId.AutoCompleteDataSource = AutoCompleteSource.ListItems;
        }
        private void ShowToolbar()
        {
            switch (CurrentMode)
            {
                case VIFON.BLL.Utilities.ControlMode.Normal:
                    ddcarlist.Enabled = txtcreatedate.Enabled = txtNotation.Enabled = txtstan.Enabled = ddCustomerId.Enabled = false;
                    ddProducts.Enabled = txtquantity.Enabled = grvproduct.Enabled = false;
                    btnCancel.Visible = false;
                    btnDelete.Visible = true;
                    btnAdd.Visible = true;
                    btnSave.Visible = false;
                    btnEdit.Visible = true;
                    txtquantity.Enabled = false;
                    btnAddproduct.Enabled = false;                    
                    txtbillid.Enabled = false;
                    ddCustomerId.Focus();
                    break;
                case VIFON.BLL.Utilities.ControlMode.New:
                    ddcarlist.Enabled = txtcreatedate.Enabled = txtNotation.Enabled = txtstan.Enabled = ddCustomerId.Enabled = true;
                    ddProducts.Enabled = txtquantity.Enabled = grvproduct.Enabled = true;
                    btnCancel.Visible = true;
                    btnDelete.Visible = false;
                    btnEdit.Visible = false;
                    btnAdd.Visible = false;
                    btnSave.Visible = true;
                    ddcarlist.Enabled = true;                    
                    txtNotation.Enabled = true;
                    txtbillid.Enabled = true;
                    txtstan.Enabled = true;
                    txtquantity.Enabled = true;
                    btnAddproduct.Enabled = true;
                  
                    break;
                case VIFON.BLL.Utilities.ControlMode.Edit:
                    ddcarlist.Enabled = txtNotation.Enabled = txtstan.Enabled = ddCustomerId.Enabled = true;
                    ddProducts.Enabled = txtquantity.Enabled = grvproduct.Enabled = true;
                    txtbillid.Enabled = true;                    
                    btnCancel.Visible = true;
                    btnDelete.Visible = false;
                    btnEdit.Visible = false;
                    btnAdd.Visible = false;
                    ddcarlist.Focus();
                    btnSave.Visible = true;
                    txtquantity.Enabled = true;
                    btnAddproduct.Enabled = true;                   
                    txtcreatedate.Enabled = true;
                    break;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            CurrentMode = VIFON.BLL.Utilities.ControlMode.New;
            txtcreatedate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
            ShowToolbar();
            grvproduct.Rows.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            int CustomerId = (int)ddCustomerId.SelectedValue;
            BillId = int.Parse(txtbillid.Text);
            string CarId = ddcarlist.Text;
            string Stan= txtstan.Text;
            string Notation=txtNotation.Text;
            DateTime CreatedDate = DateTime.Now;
            
            if(string.IsNullOrEmpty(CarId) || string.IsNullOrEmpty(Stan) || string.IsNullOrEmpty(Notation))
            {
                MessageBox.Show(Common.IsNullOrEmpty, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Bill boBill = new Bill
            {
                Id = BillId,
                CreatedDate=CreatedDate,
                CarId=CarId,
                CustomerId=CustomerId,
                Stan=Stan,
                Notation=Notation,
                CreatedDated=txtcreatedate.Text
            };     
            if (CurrentMode == VIFON.BLL.Utilities.ControlMode.New)
            {
                if (grvproduct.Rows.Count >=1)
                {
                    if (blBill.Insert(boBill))
                    {
                        CurrentMode = VIFON.BLL.Utilities.ControlMode.Normal;
                        BillDetail boBillDetail = new BillDetail();
                        foreach (var item in grvproduct.Rows)
                        {
                            boBillDetail.BillId = boBill.Id;
                            boBillDetail.ProductId = item.Cells[1].Value.ToString();
                            boBillDetail.Amounts = int.Parse(item.Cells[3].Value.ToString());
                            blBillDetails.Insert(boBillDetail);
                        }
                        ShowToolbar();                         
                        grvproduct.Rows.Clear();
                        MessageBox.Show(Common.ProcessSuccess, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtquantity.Text = "";
                    }
                    else
                        MessageBox.Show(Common.ProcessError, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Chưa chọn sản phẩm cho hóa đơn này", "Thông báo");
                    ddProducts.Focus();                
            }
            else
            {
                if (blBill.Update(boBill))
                {
                    CurrentMode = VIFON.BLL.Utilities.ControlMode.Normal;
                    ShowToolbar();
                    BillDetail boBillDetail = new BillDetail();
                    blBillDetails.Delete(BillId);
                    foreach (var item in grvproduct.Rows)
                    {
                        boBillDetail.BillId = boBill.Id;
                        boBillDetail.ProductId = item.Cells[1].Value.ToString();
                        boBillDetail.Amounts = int.Parse(item.Cells[3].Value.ToString());
                        blBillDetails.Insert(boBillDetail);
                    }
                    
                    MessageBox.Show(Common.ProcessSuccess, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    MessageBox.Show(Common.ProcessError, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);

            }            
            LoadBillList();
        }

        private void txtquantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true; 
        }

        private int testExistsProduct(string idProduct)
        {
            int rowIndex = -1;
            for (int i = 0; i < grvproduct.Rows.Count; i++)
            {
                if (grvproduct.Rows[i].Cells[1].Value.ToString() == idProduct)
                    rowIndex = i;
            }
            return rowIndex;
        }
        private void AddProduct()//add product vao gridview
        {                        
            var productId=ddProducts.SelectedValue;
            var productName = ddProducts.Text;
            var quantity = int.Parse(txtquantity.Text);
            int rowIndex = testExistsProduct(productId.ToString());
            if (rowIndex != -1)
            {
                quantity += int.Parse(grvproduct.Rows[rowIndex].Cells[3].Value.ToString());
                grvproduct.Rows[rowIndex].Cells[3].Value = quantity;
            }
            else 
            {
                grvproduct.Rows.Add(string.Empty, productId, productName, quantity);
            }
            
            //grvproduct.Rows.Add(string.Empty,productId, productName, quantity);
        }
        private void btnAddproduct_Click(object sender, EventArgs e)
        {
            if(txtquantity.Text=="")
            {
                MessageBox.Show("Nhập số lượng", "Thông báo");
                txtquantity.Focus();
            }
            else
            {
                AddProduct();     
            }           
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            CurrentMode = VIFON.BLL.Utilities.ControlMode.Edit;
            ShowToolbar();
        }

        private void grvhoadon_CellClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            
            if (e.RowIndex != -1 && grvhoadon.Columns[e.ColumnIndex].Name == "colView")
            {
                int id = int.Parse(grvhoadon.Rows[e.RowIndex].Cells["colId"].Value.ToString());
                frmShowBill showbill = new frmShowBill(id);                
                showbill.Show();
            }
            try
            {
                if (CurrentMode != BLL.Utilities.ControlMode.New)
                {
                    int rowindex = grvhoadon.CurrentCell.RowIndex;
                    txtbillid.Text = grvhoadon.Rows[rowindex].Cells[0].Value.ToString();
                    BillId = int.Parse(grvhoadon.Rows[rowindex].Cells[0].Value.ToString());
                    ddCustomerId.Text = grvhoadon.Rows[rowindex].Cells["colCustomerName"].Value.ToString();
                    ddCustomerId.SelectedValue = grvhoadon.Rows[rowindex].Cells["colCustomerId"].Value;
                    txtcreatedate.Text = grvhoadon.Rows[rowindex].Cells[3].Value.ToString();
                    ddcarlist.Text = grvhoadon.Rows[rowindex].Cells[4].Value.ToString();
                    txtstan.Text = grvhoadon.Rows[rowindex].Cells[5].Value.ToString();                   
                    txtNotation.Text = grvhoadon.Rows[rowindex].Cells[6].Value.ToString();
                }
                Loadbilldetails();
            }
            catch { }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            CurrentMode = VIFON.BLL.Utilities.ControlMode.Normal;            
            ShowToolbar();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.Yes == MessageBox.Show(Common.ConfirmDelete, Common.MessageTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                {                    
                    if (blBill.Delete(BillId))
                        MessageBox.Show(Common.ProcessSuccess, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        MessageBox.Show(Common.ProcessError, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    LoadBillList();
                }
            }
            catch
            {
                MessageBox.Show(Common.SelectRowData, Common.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnaddcarid_Click(object sender, EventArgs e)
        {
            frmCarId frmcar = new frmCarId();
            frmcar.Show();
        }

        private void txtbillid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true; 
        }

        private void MasterTemplate_KeyDown(object sender, KeyEventArgs e)
        {
            if (ModifierKeys == Keys.Delete && grvproduct.SelectedRows.Count > 0)
            {
                int RowIndex = grvproduct.CurrentRow.Index;
                grvproduct.Rows.RemoveAt(RowIndex);
            }
        }
    }
}
